import axios from 'axios'
import NProgress from 'nprogress'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import errorCode from '@/utils/errorCode'
import { getAccessToken } from '@/data/user'
import { Logger } from 'runjs/lib/common'
import eventbus from '@/utils/eventbus'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 30000
})

NProgress.configure({
  showSpinner: false
})
// request拦截器
service.interceptors.request.use(
  config => {
    NProgress.start()
    const isToken = (config.headers || {}).isToken === false
    const token = getAccessToken()
    if (token && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + token // token
    }
    // headers中配置serialize为true开启序列化
    // if (config.method === 'post' && config.headers.serialize) {
    //   config.data = serialize(config.data)
    //   // delete config.data.serialize;
    // }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(res => {
  NProgress.done()
  // console.log(`响应拦截器`, JSON.stringify(res))
  const status = Number(res.status) || 200
  const message = errorCode[status] || res.data.data || res.data.msg || errorCode['default']
  if (status === 401) {
    if (res.data.msg === 'product_invalid') {
      MessageBox.confirm(
        '系统错误',
        '系统提示',
        {
          confirmButtonText: window.i18n.t('submitText'),
          type: 'warning'
        }
      ).then(() => {
      })
    } else {
      MessageBox.confirm(
        message,
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: window.i18n.t('cancelText'),
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
    }
  } else if (status === 500) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  } else if (status !== 200 || res.data.code === 1) {
    if (res.data.data && res.data.data.programs) {
      eventbus.$emit('deteleProgram', res.data.data.programs)
      return Promise.reject(new Error(message))
    }
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))

  } else if (status == 200 && res.data.code == 1) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  else {
    return res.data
  }
},
  error => {
    NProgress.done()
    return Promise.reject(error)
  }
)

export default service
